//
//  ServiceJobsViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 14/12/2022.
//

import UIKit
import RxSwift
import RxCocoa
import RxGesture
import MJRefresh
import MJRefresh
import SwiftyJSON
import HandyJSON
import MBProgressHUD
class ServiceJobsViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    let customView = ServiceJobsView()
    var hearder: MJRefreshNormalHeader!
    var footer: MJRefreshBackNormalFooter!
    var nextPage: String = ""
    var currentPage: String = "1"
    //MARK: - job status
    var selectedJobStatus: BehaviorRelay<String> = BehaviorRelay.init(value: ServiceJobStatusName.all.rawValue)
    //MARK: - payment status
    var selectedPaymentStatus: BehaviorRelay<String> = BehaviorRelay.init(value: ServicePaymentStatusName.all.rawValue)
    
    //暂存，再此打开选项框时，设置选中项
    var selectedJobStatusStr: String = ServiceJobStatusName.all.rawValue
    var selectedPaymentStatusStr: String = ServicePaymentStatusName.all.rawValue
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUIBinding()
    }
    private func initUIBinding(){
        self.view = customView
        self.loadData()
        //MARK: - 跳转到Detail页面
        self.customView.tableView.rx.itemSelected.bind { [weak self] (indexPath) in
            guard let strongSelf = self else {return}
            let rowModel = strongSelf.customView.dataObserver.value[indexPath.row]
            let vc = ServiceJobDetailViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.reloadServiceJobsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadData(loadingFlag: false, pageSize: strongSelf.customView.dataObserver.value.count)
            }
            ServiceDetailModelHelper.shared.serviceDetailModel = ServiceDetailModel()
            ServiceDetailModelHelper.shared.serviceDetailModel.id = rowModel.id
            
            strongSelf.navigationController?.pushViewController(vc, animated: false)
        }.disposed(by: disposeBag)
        
        //上拉加载，下来刷新
        self.hearder =  MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        self.customView.tableView.mj_header = self.hearder
        //footer
        self.footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerLoad(_:)))
        self.customView.tableView.mj_footer = self.footer
        //点击头像
        self.customView.topCommonView.avatarImageView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            InstallationDetailVCHelper.shared.toMeViewController(strongSelf)
        }).disposed(by: self.disposeBag)
        //点击search按钮
        self.customView.topCommonView.searchBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.searchBtnClick()
        }).disposed(by: disposeBag)
        //订阅job status的变化，反应在label上
        selectedJobStatus.subscribe(onNext: { text in
            self.customView.searchJobStatusLabel.text = text
        }).disposed(by: self.disposeBag)
        //订阅payment status的变化，反应在label上
        selectedPaymentStatus.subscribe(onNext: { text in
            self.customView.searchPaymentStatusLabel.text = text
        }).disposed(by: self.disposeBag)
        
        //点击job status显示
        self.customView.searchJobStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.showStatusPopView()
        }).disposed(by: self.disposeBag)
        //点击payment status显示
        self.customView.searchPaymentStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.showStatusPopView()
        }).disposed(by: self.disposeBag)
    }
    //MARK: - 点击显示所有Job的状态
    private func showStatusPopView(){
        let view = ServieJobStatusPopView()
        view.initData(jobStatus: self.selectedJobStatusStr, paymentStatus: self.selectedPaymentStatusStr)
        view.applyClosure = {[weak self] (jobStatus,paymentStatus) in
            guard let strongSelf = self else { return  }
            strongSelf.selectedJobStatusStr = jobStatus
            strongSelf.selectedPaymentStatusStr = paymentStatus
            //job status
            if jobStatus.contains(ServiceJobStatusName.scheduled.rawValue + ",") && jobStatus.contains(ServiceJobStatusName.started.rawValue + ",")  && jobStatus.contains(ServiceJobStatusName.unqualified.rawValue + ",") && jobStatus.contains(ServiceJobStatusName.approved.rawValue + ",") && jobStatus.contains(ServiceJobStatusName.finished.rawValue + ","){//五个状态全选，则默认all
                strongSelf.selectedJobStatus.accept(ServiceJobStatusName.all.rawValue)
            }else{
                var realStatus = jobStatus
                if jobStatus.contains(",") {
                    realStatus = String(jobStatus.prefix(jobStatus.count - 1))//去掉最后的逗号
                }
                strongSelf.selectedJobStatus.accept(realStatus)//去掉最后的逗号
            }
            //payment status
            if paymentStatus.contains(ServicePaymentStatusName.open.rawValue + ",") && paymentStatus.contains(ServicePaymentStatusName.paid.rawValue + ",")  {//两个type全选，则默认all
                strongSelf.selectedPaymentStatus.accept(ServicePaymentStatusName.all.rawValue)
            }else{
                var realPaymentStatus = paymentStatus
                if paymentStatus.contains(",") {
                    realPaymentStatus = String(paymentStatus.prefix(paymentStatus.count - 1))//去掉最后的逗号
                }
                strongSelf.selectedPaymentStatus.accept(realPaymentStatus)
            }
            strongSelf.loadData()
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    func loadData(loadingFlag: Bool = true,header: MJRefreshNormalHeader? = nil, footer: MJRefreshBackNormalFooter? = nil,pageSize: Int? = nil){
        //set block
        let vm = MyBidJobsListViewModel()
        
        vm.setBlockAfterNetwork { result, otherInfo in
            header?.endRefreshing()
            footer?.endRefreshing()
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }

            //header data
            if let pageInfo = otherInfo {
                self.nextPage = pageInfo.object(forKey: "X-Next-Page") as? String ?? ""
            }
            if self.nextPage != "" {
                self.footer.resetNoMoreData()
            }else{
                self.footer.endRefreshingWithNoMoreData()
            }
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<ServiceJobListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<ServiceJobListModel>{
                if self.currentPage == "1" {
                    self.customView.dataObserver.accept(data)
                }else{
                    let temp = data
                    self.customView.dataObserver.accept(self.customView.dataObserver.value + temp)
                }
                //没有数据显示not data view，有数据隐藏not data view
                self.customView.tableView.showResultView(nodataFlag: self.customView.dataObserver.value.count == 0 ? true: false)
            }
        } errorBlock: { code, error in
            header?.endRefreshing()
            footer?.endRefreshing()
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            Tool().showErrorInfo(code, error)
        }
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView(R.string.localizable.loading())
        }
        if let tempHeader = header {
            tempHeader.beginRefreshing()
        }
        if let tempFooter = footer {
            tempFooter.beginRefreshing()
        }
        //add Loading view
        var combineStr = "?page=" + self.currentPage + self.getQueryStr()
        if let page = pageSize {
            combineStr += "&per_page=\(page)"//从detail返回刷新list用
        }
        vm.getMyBidJobsList(combineStr)
    }
    private func getQueryStr()->String{
        var queryStr = ""
        if self.selectedJobStatus.value != ServiceJobStatusName.all.rawValue {
            queryStr += "&status=" + self.selectedJobStatus.value
        }
        if self.selectedPaymentStatus.value != ServicePaymentStatusName.all.rawValue {
            queryStr += "&payment_status=" + self.selectedPaymentStatus.value
        }
        
        return queryStr
    }
    @objc func headerLoad(_ header: MJRefreshNormalHeader){
        self.currentPage = "1"
        self.loadData(loadingFlag: false, header: header)
    }
    
    @objc func footerLoad(_ footer: MJRefreshBackNormalFooter){
        self.currentPage = self.nextPage
        self.loadData(loadingFlag: false,footer: footer)
        
    }
    func searchBtnClick(){
        let vc = JobsListSearchViewController()
        vc.searchModule = .serviceJobs
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func refreshData(){
        self.currentPage = "1"
        self.loadData(loadingFlag: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
